import paho.mqtt.client as paho
import logging
import json

_log = None


class MqttClient:
    def __init__(self, config: dict) -> None:
        global _log
        self._config = config
        self.ip = config["host"]
        self.port = config["port"]
        _log = logging.getLogger('mqtt')
        self._client = paho.Client(protocol=paho.MQTTv311)
        self._client.on_connect = lambda _, __, ____, rc: self.on_connect_cb(rc)

    def on_connect_cb(self, rc: int):
        _log.info("Connected mqtt broker %s with result: %d", self._config["host"], rc)

    def send_msg(self,  msg: dict, qos:int = 0,topic: str = ATTRIBUTES_TOPIC):
        payload = json.dumps(msg)
        # print(f"mqtt发送数据topic:{topic},payload:{payload}")
        _log.debug("topic:",topic,"payload:",payload)
        self._client.publish(topic, payload, qos)

    def start(self):
        if "accessToken" in self._config:
            self._client.username_pw_set(self._config["accessToken"], password=None)
        self._client.connect_async(self._config["host"], self._config["port"], 60)
        self._client.loop_start()
    
    def stop(self):
        self._client.loop_stop()